import React, { useEffect, useState } from 'react';
import { Card, Table, Tag, Space, message } from 'antd';
import { useUserStore } from '../../store/userStore';
import axios from 'axios';

interface CompletedTask {
  title: string;
  description: string;
  category: string;
  reward: {
    greenEnergy: number;
    carbonReduction: number;
    waterQuality: number;
  };
  finishAt: string;
}

const DataCenter: React.FC = () => {
  const [completedTasks, setCompletedTasks] = useState<CompletedTask[]>([]);

  useEffect(() => {
    fetchCompletedTasks();
  }, []);

  const fetchCompletedTasks = async () => {
    try {
      const userId = localStorage.getItem('userId');
      const response = await axios.get(`http://localhost:3001/api/tasks/completed?userId=${userId}`);
      setCompletedTasks(response.data);
    } catch (error) {
      message.error('获取已完成任务失败');
    }
  };

  const columns = [
    {
      title: '完成时间',
      dataIndex: 'finishAt',
      key: 'finishAt',
      render: (date: string) => {
        const dateObj = new Date(date);
        return isNaN(dateObj.getTime()) ? '无效日期' : dateObj.toLocaleString('zh-CN');
      },
    },
    {
      title: '任务名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '类型',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => (
        <Tag color={category === '个性化挑战' ? 'green' : 'blue'}>
          {category}
        </Tag>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '碳减排量',
      dataIndex: 'reward',
      key: 'carbonReduction',
      render: (reward: any) => `${reward.carbonReduction.toFixed(2)} kg CO₂`,
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card title="碳足迹数据中心" style={{ marginBottom: '24px' }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div>
            <h3>已完成任务</h3>
            <Table
              columns={columns}
              dataSource={completedTasks}
              rowKey="_id"
              pagination={{ pageSize: 10 }}
            />
          </div>
        </Space>
      </Card>
    </div>
  );
};

export default DataCenter;